import React from "react";
import ReactDOMServer from "react-dom/server";
import * as widgets from "../widgets";
import { createRenderWidget } from "../widgets/context";

const renderWidget = async (widget, params, query) => {
    const { widgetId, Component, getInitState, renderMode, reducer } = widget;
    let widgetString = "";
    let state = {};
    if (renderMode === "server") {
        state = await Promise.resolve(getInitState(params, query));
        const Widget = createRenderWidget(Component, state, reducer);
        widgetString = ReactDOMServer.renderToString(<Widget />);
    }
    return `
        <div id="${widgetId}--widget" reqInfo='${JSON.stringify({ params, query })}' state='${JSON.stringify(state)}'>${widgetString}</div>
    `
}

class PageRender {
    constructor(req, res) {
        this.params = req.params;
        this.query = req.query;
        this.widgets = [];
    }

    async render() {
        this.addWidgets();
        const s = await Promise.all(this.widgets.map(widget => renderWidget(widget, this.params, this.query)));
        return `<!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8" />
            <title>Isomorphic React</title>
            
            <link href="/assets/client.css" rel="stylesheet" />
            <script src="/react.js" type="text/javascript"></script>
            <script src="/react-dom.js" type="text/javascript"></script>
        </head>
        <body>
            <div id="app">${s.join("")}</div>
            <script src="/assets/vendor.js" type="text/javascript"></script>
            <script src="/assets/runtime.js" type="text/javascript"></script>
            <script src="/assets/client.js" type="text/javascript"></script>
        </body>
        </html>

        `;
    }
}

class HomePageRender extends PageRender {
    constructor(req, res) {
        super(req, res);
    }

    addWidgets() {
        Object.keys(widgets).forEach(key => {
            this.widgets.push(widgets[key]);
        });
    }
}
class SectorPageRender extends PageRender {
    constructor(req, res) {
        super(req, res);
    }

    addWidgets() {
        this.widgets.push(w.Sector);
    }
}

export { PageRender, HomePageRender, SectorPageRender };